package com.aerozhonghuan.oknet2;

import android.text.TextUtils;

import org.json.JSONException;
import org.json.JSONObject;


/**
 * CommonMessage Parser
 * Created by songzhongkun on 15/9/24.
 */
public class CommonMessageParser {
    private static final String TAG = CommonMessageParser.class.getSimpleName();

    /**
     * 解析成实体
     *
     * @param responseString responseString
     * @return CommonMessage
     * @throws JSONException ex
     */
    public static CommonMessage parse(String responseString) throws JSONException {
        if (responseString == null)
            return null;
        JSONObject object = new JSONObject(responseString);
        String code = object.optString("resultCode");
        if (TextUtils.isEmpty(code)) {
            code = object.optString("code");
        }
        if (TextUtils.isEmpty(code)) {
            code = object.optString("status");
        }
        if (TextUtils.isEmpty(code)) {
            boolean success = object.optBoolean("success");
            if (success) {
                code = "200";
            } else {
                code = "508";
            }
        }
        String errmsg = object.optString("message");
        if (TextUtils.isEmpty(errmsg)) {
            errmsg = object.optString("msg");
        }
        if (TextUtils.isEmpty(errmsg)) {
            errmsg = object.optString("emsg");
        }
        String body = "";
        if (object.has("data")) {
            body = object.optString("data");
        }
        CommonMessage entity = new CommonMessage();
        if (TextUtils.isEmpty(code))
            throw new JSONException("远程服务意外的返回内容：code = 空");
        entity.code = Integer.parseInt(code);
        entity.message = errmsg == null ? "" : errmsg;
        entity.data = body == null ? "" : body;
        return entity;
    }


}
